'use client';

import { useRouter, useParams } from 'next/navigation';
import { useEffect, useState } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Receipt, ArrowLeft } from 'lucide-react';
import { formatMoney, formatDate, getApiUrl } from '@/lib/utils';
import { toast } from '@/components/ui/use-toast';
import Link from 'next/link';

const expenseTypeMap = {
  material: '材料费',
  labor: '人工费',
  equipment: '设备费',
  other: '其他费用'
} as const;

type ExpenseType = keyof typeof expenseTypeMap;

interface Expense {
  id: string;
  siteId: string;
  type: ExpenseType;
  amount: number;
  paymentDate: string;
  vendor: string | null;
  description: string | null;
  site: {
    id: string;
    name: string;
  };
}

export default function DeleteExpensePage() {
  const router = useRouter();
  const params = useParams();
  const id = params.id as string;
  const [expense, setExpense] = useState<Expense | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isDeleting, setIsDeleting] = useState(false);

  useEffect(() => {
    async function loadExpense() {
      try {
        const response = await fetch(getApiUrl(`expenses/${id}`));
        if (!response.ok) throw new Error('加载支出详情失败');
        const data = await response.json();
        setExpense(data);
      } catch {
        toast({
          variant: 'destructive',
          title: '加载失败',
          description: '无法加载支出详情，请刷新页面重试',
        });
      } finally {
        setIsLoading(false);
      }
    }
    loadExpense();
  }, [id]);

  async function handleDelete() {
    if (!expense || isDeleting) return;

    setIsDeleting(true);
    try {
      const response = await fetch(getApiUrl(`expenses/${id}`), {
        method: 'DELETE',
      });

      if (!response.ok) {
        throw new Error('删除失败');
      }

      toast({
        title: '删除成功',
        description: '支出记录已删除',
      });

      router.push('/expenses');
      router.refresh();
    } catch {
      toast({
        variant: 'destructive',
        title: '删除失败',
        description: '请稍后重试',
      });
      setIsDeleting(false);
    }
  }

  if (isLoading) {
    return <div>加载中...</div>;
  }

  if (!expense) {
    return <div>支出记录不存在</div>;
  }

  return (
    <main className="container mx-auto p-4 space-y-4">
      <Button variant="ghost" asChild className="mb-4">
        <Link href={`/expenses/${id}`}>
          <ArrowLeft className="mr-2 h-4 w-4" />
          返回支出详情
        </Link>
      </Button>

      <div className="max-w-xl mx-auto space-y-6">
        <div>
          <h1 className="text-3xl font-bold tracking-tight text-destructive">删除支出</h1>
          <p className="text-muted-foreground mt-2">
            您确定要删除这条支出记录吗？此操作无法撤销。
          </p>
        </div>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">支出详情</CardTitle>
            <Receipt className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <div className="text-sm text-muted-foreground">支出金额</div>
              <div className="text-xl font-bold">{formatMoney(expense.amount)}</div>
            </div>

            <div>
              <div className="text-sm text-muted-foreground">所属工地</div>
              <div className="text-xl font-bold">{expense.site.name}</div>
            </div>

            <div>
              <div className="text-sm text-muted-foreground">支出类型</div>
              <div className="text-xl font-bold">{expenseTypeMap[expense.type]}</div>
            </div>

            <div>
              <div className="text-sm text-muted-foreground">支付时间</div>
              <div className="text-xl font-bold">{formatDate(expense.paymentDate)}</div>
            </div>

            {expense.vendor && (
              <div>
                <div className="text-sm text-muted-foreground">供应商</div>
                <div className="text-xl font-bold">{expense.vendor}</div>
              </div>
            )}

            {expense.description && (
              <div>
                <div className="text-sm text-muted-foreground">备注说明</div>
                <div className="text-xl font-bold">{expense.description}</div>
              </div>
            )}
          </CardContent>
        </Card>

        <div className="flex gap-4">
          <Button
            variant="destructive"
            onClick={handleDelete}
            disabled={isDeleting}
          >
            {isDeleting ? '删除中...' : '确认删除'}
          </Button>
          <Button
            variant="outline"
            onClick={() => router.back()}
            disabled={isDeleting}
          >
            取消
          </Button>
        </div>
      </div>
    </main>
  );
}